package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import dao.CartDao;
import po.Cart;
import util.DBUtil;

public class CartDaoImpl implements CartDao {

	@Override
	public Integer addCart(Cart cart) {
		Connection con = null;
		PreparedStatement pst = null;
		int count = 0;
		
		try {
			con = DBUtil.getConnection();
			con.setAutoCommit(false);
			String sql = "insert into cart(id,aid,did,count) values(CART_SEQ.nextval,?,?,?)";
			pst = con.prepareStatement(sql);
			pst.setString(1,cart.getAid());
			pst.setInt(2, cart.getDid());
			pst.setInt(3,cart.getCount());
			count = pst.executeUpdate();
			con.commit();
		} catch (SQLException e) {
			try {
				con.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			DBUtil.close(con, pst, null);
		}
		return count;
	}
	
	public boolean findCart(Cart cart){
		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		boolean flag = false;
		try {
			con = DBUtil.getConnection();
			String sql = "select count(1) from cart where aid = ? and did = ";
			pst = con.prepareStatement(sql);
			pst.setString(1, cart.getAid());
			rs = pst.executeQuery();
			while (rs.next()) {
				flag = true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(con, pst, rs);
		}
		return flag;
	}

	@Override
	public Map<Integer,Integer> findCartByAid(String aid) {
		Connection con = null;
		PreparedStatement pst = null;
		ResultSet rs = null;
		Cart cart = null;
		Map<Integer,Integer> map = null;
		try {
			map = new HashMap<Integer,Integer>();
			con = DBUtil.getConnection();
			String sql = "select did,count from cart where aid = ? ";
			pst = con.prepareStatement(sql);
			pst.setString(1, aid);
			rs = pst.executeQuery();
			while (rs.next()) {
				map.put(rs.getInt("did"), rs.getInt("count"));
			}
			truncateCartByAid(aid);
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			DBUtil.close(con, pst, rs);
		}
		return map;
	}
	
	public int truncateCartByAid(String aid){
		String sql = "delete from cart where aid = ? ";
		Connection con = null;
		PreparedStatement pst = null;
		int m = 0;
		try {
			con = DBUtil.getConnection();
			pst = con.prepareStatement(sql);
			con.setAutoCommit(false);
			pst.setString(1, aid);
			m = pst.executeUpdate();
			con.commit();
		} catch (SQLException e) {
			try {
				con.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
			e.printStackTrace();
		} finally {
			DBUtil.close(con, pst, null);
		}
		return m;
		
	}

}
